<template>
  <div>
    <a-input-search
      v-model="selectedCustomerName"
      :placeholder="placeholder"
      :disabled="disabled"
      readOnly
      @search="handleSearch">
      <a-button slot="enterButton" :disabled="disabled">选择</a-button>
    </a-input-search>
    <a-modal
      :title="title"
      :width="modalWidth"
      :visible="visible"
      :confirmLoading="confirmLoading"
      @ok="handleOk"
      @cancel="handleCancel"
      :class="'jee-outer-modal'">
      
      <a-spin :spinning="confirmLoading">
        <!-- 查询区域 -->
        <div class="query-area">
          <a-form layout="inline">
            <a-row :gutter="24" style="margin-bottom: 8px">
              <a-col :md="8" :sm="24">
                <a-form-item label="客户名称">
                  <a-input placeholder="请输入客户名称" v-model="queryParam.customerName" allowClear></a-input>
                </a-form-item>
              </a-col>
              <a-col :md="8" :sm="24">
                <a-form-item label="联系人">
                  <a-input placeholder="请输入联系人" v-model="queryParam.contactPerson" allowClear></a-input>
                </a-form-item>
              </a-col>
              <a-col :md="8" :sm="24">
                <a-form-item label=" ">
                  <span class="table-page-search-submitButtons">
                    <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
                    <a-button style="margin-left: 8px" @click="searchReset" icon="reload">重置</a-button>
                  </span>
                </a-form-item>
              </a-col>
            </a-row>
            <a-row :gutter="24">
              <a-col :md="8" :sm="24">
                <a-form-item label="省份">
                  <a-select
                    placeholder="请选择省份"
                    v-model="queryParam.provinceCode"
                    @change="handleProvinceChange"
                    :getPopupContainer="getParentModal"
                    allowClear
                  >
                    <a-select-option v-for="(name, code) in provinceOptions" :key="code" :value="code">
                      {{ name }}
                    </a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :md="8" :sm="24">
                <a-form-item label="城市">
                  <a-select
                    placeholder="请选择城市"
                    v-model="queryParam.cityCode"
                    @change="handleCityChange"
                    :disabled="!queryParam.provinceCode"
                    :getPopupContainer="getParentModal"
                    allowClear
                  >
                    <a-select-option v-for="(name, code) in cityOptions" :key="code" :value="code">
                      {{ name }}
                    </a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :md="8" :sm="24">
                <a-form-item label="区县">
                  <a-select
                    placeholder="请选择区县"
                    v-model="queryParam.areaCode"
                    :disabled="!queryParam.cityCode"
                    :getPopupContainer="getParentModal"
                    allowClear
                  >
                    <a-select-option v-for="(name, code) in areaOptions" :key="code" :value="code">
                      {{ name }}
                    </a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
            </a-row>
          </a-form>
        </div>
        
        <!-- 表格区域 -->
        <div style="margin-bottom: 10px;">
          <a-button type="primary" icon="plus" @click="handleAddCustomer">新增客户</a-button>
        </div>
        <a-table
          ref="table"
          size="middle"
          bordered
          rowKey="id"
          :columns="columns"
          :dataSource="dataSource"
          :pagination="ipagination"
          :loading="loading"
          :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange, type: multiple ? 'checkbox' : 'radio'}"
          @change="handleTableChange">
        </a-table>
      </a-spin>
    </a-modal>

    <!-- 新增客户模态框 -->
    <customer-modal ref="customerModal" @ok="handleCustomerCreated"></customer-modal>
  </div>
</template>

<script>
  import { getAction } from '@/api/manage'
  import CustomerModal from '@/views/crm/modules/CustomerModal'
  
  export default {
    name: 'JSelectCustomerModal',
    components: {
      CustomerModal
    },
    props: {
      value: {
        type: String,
        default: ''
      },
      placeholder: {
        type: String,
        default: '请选择客户'
      },
      disabled: {
        type: Boolean,
        default: false
      },
      modalWidth: {
        type: Number,
        default: 1000
      },
      multiple: {
        type: Boolean,
        default: false
      },
      title: {
        type: String,
        default: '选择客户'
      }
    },
    data() {
      return {
        visible: false,
        confirmLoading: false,
        selectedRowKeys: [],
        selectedCustomerId: '', // 保存选择的客户ID
        selectedCustomerName: '', // 保存选择的客户名称
        selectedCustomer: null, // 保存选择的客户信息
        
        // 查询条件
        queryParam: {
          customerName: '',
          contactPerson: '',
          provinceCode: '',
          cityCode: '',
          areaCode: ''
        },
        
        // 省市区选择
        areaCode: [],
        
        // 省市区数据
        provinceOptions: {},
        cityOptions: {},
        areaOptions: {},
        
        // 数据源
        dataSource: [],
        
        // 表格列
        columns: [
          {
            title: '客户名称',
            dataIndex: 'customerName',
            width: '20%',
            align: 'center'
          },
          {
            title: '联系人',
            dataIndex: 'contactPerson',
            width: '10%',
            align: 'center'
          },
          {
            title: '联系电话',
            dataIndex: 'contactPhone',
            width: '15%',
            align: 'center'
          },
          {
            title: '地区',
            dataIndex: 'area',
            width: '20%',
            align: 'center',
            customRender: (text, record) => {
              return [record.provinceName, record.cityName, record.areaName].filter(Boolean).join(' / ');
            }
          },
          {
            title: '地址',
            dataIndex: 'address',
            width: '25%',
            align: 'center'
          },
        ],
        
        // 分页参数
        ipagination: {
          current: 1,
          pageSize: 10,
          pageSizeOptions: ['10', '20', '30'],
          showTotal: (total, range) => {
            return range[0] + '-' + range[1] + ' 共' + total + '条'
          },
          showQuickJumper: true,
          showSizeChanger: true,
          total: 0
        },
        
        loading: false,
        url: {
          list: '/crm/customer/list',
          getById: '/crm/customer/queryById'
        }
      }
    },
    watch: {
      value: {
        immediate: true,
        handler(val) {
          if (val) {
            this.initSelectedCustomer(val);
          } else {
            this.selectedCustomerId = '';
            this.selectedCustomerName = '';
            this.selectedCustomer = null;
            this.selectedRowKeys = [];
          }
        }
      }
    },
    mounted() {
      // 获取省份列表
      this.loadProvinceData();
    },
    methods: {
      // 初始化已选择的客户信息
      initSelectedCustomer(selectedId) {
        if (!selectedId) return;
        
        this.loading = true;
        getAction(this.url.getById, { id: selectedId }).then(res => {
          if (res.success) {
            this.selectedCustomer = res.result;
            this.selectedCustomerId = this.selectedCustomer.id;
            this.selectedCustomerName = this.selectedCustomer.customerName;
            this.selectedRowKeys = [this.selectedCustomerId];
            
            // 移除初始化省市区数据的代码
            // 保持与onSelectChange方法一致，不自动填充查询条件
          }
        }).finally(() => {
          this.loading = false;
        });
      },
      
      // 打开选择框
      handleSearch() {
        if (this.disabled) return;
        
        this.visible = true;
        this.loadData(1);
      },
      
      // 加载数据
      loadData(arg) {
        if (arg === 1) {
          this.ipagination.current = 1;
        }
        
        const params = this.getQueryParams();
        this.loading = true;
        
        getAction(this.url.list, params).then(res => {
          if (res.success) {
            this.dataSource = res.result.records || [];
            this.ipagination.total = res.result.total || 0;
          }
        }).finally(() => {
          this.loading = false;
        });
      },
      
      // 获取查询参数
      getQueryParams() {
        const param = Object.assign({}, this.queryParam);
        param.pageNo = this.ipagination.current;
        param.pageSize = this.ipagination.pageSize;
        return param;
      },
      
      // 选择改变
      onSelectChange(selectedRowKeys, selectedRows) {
        this.selectedRowKeys = selectedRowKeys;
        
        if (!this.multiple) {
          this.selectedCustomer = selectedRows[0];
          
          // 移除自动填充省市区信息的代码
          // 选择客户时不应该影响已有的查询条件
        } else {
          // 多选模式
          this.selectedCustomer = selectedRows;
        }
      },
      
      // 查询按钮
      searchQuery() {
        this.loadData(1);
      },
      
      // 重置按钮
      searchReset() {
        this.queryParam = {
          customerName: '',
          contactPerson: '',
          provinceCode: undefined,
          cityCode: undefined,
          areaCode: undefined
        };
        this.cityOptions = {};
        this.areaOptions = {};
        this.loadData(1);
      },
      
      // 表格分页、排序、筛选变化
      handleTableChange(pagination, filters, sorter) {
        this.ipagination.current = pagination.current;
        this.ipagination.pageSize = pagination.pageSize;
        this.loadData();
      },
      
      // 确定按钮
      handleOk() {
        if (!this.selectedCustomer) {
          this.$message.warning('请选择客户');
          return;
        }
        
        if (!this.multiple) {
          this.selectedCustomerId = this.selectedCustomer.id;
          this.selectedCustomerName = this.selectedCustomer.customerName;
          
          this.$emit('input', this.selectedCustomerId);
          this.$emit('change', this.selectedCustomerId, this.selectedCustomer);
        } else {
          // 多选模式
          const ids = this.selectedCustomer.map(item => item.id);
          const names = this.selectedCustomer.map(item => item.customerName);
          
          this.selectedCustomerId = ids.join(',');
          this.selectedCustomerName = names.join(',');
          
          this.$emit('input', this.selectedCustomerId);
          this.$emit('change', this.selectedCustomerId, this.selectedCustomer);
        }
        
        this.handleCancel();
      },
      
      // 取消按钮
      handleCancel() {
        this.visible = false;
      },
      
      // 加载省份数据
      loadProvinceData() {
        this.provinceOptions = this.$Jpcaa['86'] || {};
      },
      
      // 处理省份选择变更
      handleProvinceChange(value) {
        // 清空市和区的选择
        this.queryParam.cityCode = undefined;
        this.queryParam.areaCode = undefined;
        this.areaOptions = {};
        
        if (value) {
          // 加载该省份下的城市
          this.cityOptions = this.$Jpcaa[value] || {};
        } else {
          this.cityOptions = {};
        }
      },
      
      // 处理城市选择变更
      handleCityChange(value) {
        // 清空区的选择
        this.queryParam.areaCode = undefined;
        
        if (value) {
          // 加载该城市下的区县
          this.areaOptions = this.$Jpcaa[value] || {};
        } else {
          this.areaOptions = {};
        }
      },
      
      // 获取父级Modal元素，解决下拉框被遮挡的问题
      getParentModal() {
        return document.querySelector('.jee-outer-modal');
      },

      // 新增客户按钮
      handleAddCustomer() {
        this.$refs.customerModal.show();
      },

      // 新增客户成功后的处理
      handleCustomerCreated() {
        this.loadData(1);
      },
    }
  }
</script>

<style scoped>
  .query-area {
    margin-bottom: 16px;
    background-color: #fafafa;
    padding: 16px 16px 0 16px;
    border-radius: 4px;
  }
  
  .table-page-search-submitButtons {
    display: flex;
    align-items: center;
    width: 100%;
  }
  
  /* 表单项样式优化 */
  ::v-deep .ant-form-item {
    margin-bottom: 16px;
    width: 100%;
  }
  
  ::v-deep .ant-form-item-label {
    line-height: 32px;
    min-width: 70px;
    width: 70px;
    text-align: right;
    padding-right: 8px;
    white-space: nowrap;
    display: inline-block;
  }
  
  ::v-deep .ant-form-item-control {
    line-height: 32px;
    flex: 1;
  }
  
  ::v-deep .ant-select {
    width: 100%;
  }
  
  /* 表格样式优化 */
  ::v-deep .ant-table-wrapper {
    margin-top: 8px;
  }
  
  ::v-deep .ant-table-bordered .ant-table-thead > tr > th {
    background-color: #fafafa;
  }

  /* 省市区下拉框样式 */
  ::v-deep .ant-form-item {
    margin-bottom: 16px;
    width: 100%;
  }

  ::v-deep .ant-col-md-8 {
    display: flex;
  }

  ::v-deep .ant-form-item-control-wrapper {
    width: 100%;
  }
  
  /* 统一下拉框和输入框宽度 */
  ::v-deep .ant-select {
    width: 100%;
  }
  
  ::v-deep .ant-input {
    width: 100%;
  }
  
  /* 确保每行表单项布局一致 */
  ::v-deep .ant-row {
    display: flex;
    flex-wrap: wrap;
  }
  
  /* 调整label为空的表单项，使其对齐 */
  ::v-deep .ant-form-item-label > label:empty {
    display: none;
  }
  
  ::v-deep .ant-form-item-label > label:empty + .ant-form-item-children {
    padding-top: 4px; /* 微调使按钮与输入框对齐 */
  }
</style> 